package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.mapper.RoleMapper;
import com.example.demo.mapper.UserMapper;
import com.example.demo.mapper.UserRoleMapper;
import com.example.demo.pojo.Role;
import com.example.demo.pojo.SysUser;
import com.example.demo.service.UserService;
import com.example.demo.util.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, SysUser> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    RoleMapper roleMapper;


    @Override
    public SysUser login(String username, String password) {
        return userMapper.login(username,password);
    }

    @Override
    public boolean addUser(SysUser sysUser) {
        int insert = userMapper.insert(sysUser);
        if(insert>0){
            return true;
        }
        return false;


//        this.addUser(user);
//        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
//
//        wrapper.eq("id",1);
//
//
//        userMapper.update(user,wrapper);



    }

    @Override
    public SysUser getUserById(Long id) throws ServiceException {
//        if(true){
//            throw new ServiceException("id不能为空");
//        }
        return userMapper.selectById(id);
    }

    @Override
    public List<SysUser> getUserALl() {
        return userMapper.selectList(null);
    }

    @Override
    public void deleteUserById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public void saveUser(SysUser sysUser) {
        //user  Id不为空是修改  id是空是添加
        this.saveOrUpdate(sysUser);
    }

    @Override
    public SysUser getUserByUserName(String username) {
        if(StringUtils.hasText(username)){
            //条件构造器
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("username",username);
            SysUser sysUser = userMapper.selectOne(qw);
            List<Role> roles = roleMapper.getRolesByUserId(sysUser.getId());
            sysUser.setRoles(roles);
            return sysUser;
        }
        return null;
    }


}
